<template>
  <div class="YRichTextBlock">
    <quill-editor
      ref="myQuillEditor"
      class="YRichText"
      :class="{ 'quill-disabled': disabled }"
      @focus="(e) => { if(disabled){ e.enable(false) } }"
      v-model="content"
      :options="editorOption"
    ></quill-editor>
    <el-upload
      v-if="video"
      ref="yUpload"
      style="display: none"
      action=""
      :show-file-list="false"
      :http-request="() => {}"
      :multiple="false"
      :on-change="onVideoUploadChange"
      :limit="1"
      accept="video/mp4"
      :auto-upload="false">
      <el-button type="primary" size="mini" ref="uploadBtn"></el-button>
    </el-upload>
  </div>
</template>

<script>
import 'quill-paste-smart';
import { Quill } from 'vue-quill-editor';
import Video from './RichVideo'
import ImageUploader from "./quill-image-uploader/quill.imageUploader";

Quill.register("modules/imageUploader", ImageUploader);
Quill.register(Video, true);
export default {
  name: "YRichText",
  inject: ['File2ArrayBuffer', 'generateMediaUrl', 'dataURLtoBlob', 'defaultUploadChange'],
  computed:{
    content:{
      get(){
        return this.value;
      },
      set(val){
        this.$emit("change", val)
      }
    },
    editorOption(){
      let option = {
        modules: {
          //禁止粘贴图片/视频等
          clipboard: {
            allowed: {
              tags: ['a', 'b', 'strong', 'u', 's', 'i', 'p', 'br', 'ul', 'ol', 'li', 'span'],
              attributes: ['href', 'rel', 'target', 'class']
            },
            keepSelection: false,
            substituteBlockElements: true,
            magicPasteLinks: true,
            /*hooks: {
              uponSanitizeElement(node, data, config) {
                console.log(node);
              },
            },*/
          },
          //图片上传
          imageUploader: {
            preUpload: (function(file){
              if(!file.type.startsWith('image/')){
                this.$message({
                  type: 'warning',
                  message: '只允许上传图片'
                });
                return false;
              }
              return true;
            }).bind(this),
            upload: (file) => {
              return new Promise((resolve, reject) => {
                this.defaultUploadChange({
                  status: 'ready',
                  raw: file,
                  size: file.size,
                  name: file.name
                }, info => {
                  resolve(this.generateMediaUrl(info));
                }, e => {
                  this.$message({
                    type: 'danger',
                    message: '上传错误，请联系管理员'
                  });
                  reject();
                });
              });
            },
          },
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],        // 加粗，斜体，下划线，删除线
              [{ 'list': 'ordered'}, { 'list': 'bullet' }],     // 有序列表，无序列表
              [{ 'indent': '-1'}, { 'indent': '+1' }],          // 缩进
              [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
              [{ 'color': [] }, { 'background': [] }],          // 颜色选择
              [{ 'font': [] }],// 字体
              [{ 'align': [] }] // 居中
            ],
            handlers:{
              video: value => {
                if(value){
                  this.$refs['uploadBtn'].$el.click();
                }else{
                  this.$refs['myQuillEditor'].quill.format("video", false);
                }
              }
            }
          }
        }
      }
      if(this.img && this.video){
        option.modules.toolbar.container.push(['image'], ['video']);
        option.placeholder = this.placeholder || '请上传图片/视频或者输入文字';
      }else if(this.img){
        option.modules.toolbar.container.push(['image']);
        option.placeholder = this.placeholder || '请上传图片或者输入文字';
      }else if(this.video){
        option.modules.toolbar.container.push(['video']);
        option.placeholder = this.placeholder || '请上传视频或者输入文字';
      }else{
        option.placeholder = this.placeholder || '请输入文字';
      }
      if(this.disabled){
        option.readOnly = true;
      }
      return option;
    }
  },
  model:{
    prop: 'value',
    event: 'change'
  },
  mounted(){ this.doWatchDisabled() },
  props:{
    value: String,
    businessSysModuleCode: String,
    placeholder: String,
    disabled:{
      type: Boolean,
      default: false
    },
    img: {
      type: Boolean,
      default: true
    },
    video: {
      type: Boolean,
      default: false
    }
  },
  methods:{
    doWatchDisabled(){
      this.$refs['myQuillEditor'] && this.$refs['myQuillEditor'].quill.enable(!this.disabled)
    },
    onVideoUploadChange(fileObj){
      if(!fileObj.name.endsWith('mp4') && !fileObj.name.endsWith('MP4')){
        this.$message({
          type: 'warning',
          message: `仅支持上传mp4格式的视频`
        });
        this.$refs['yUpload'].clearFiles();
        return;
      }
      if(fileObj.size > this.limitSize * 1024 * 1024){
        this.$message({
          type: 'warning',
          message: `文件大小超出限制：${this.limitSize}mb`
        });
        this.$refs['yUpload'].clearFiles();
        return;
      }
      this.defaultUploadChange(fileObj, info => {
        let selection = this.$refs['myQuillEditor'].quill.getSelection()
        let index = selection ? selection.index : 0;
        let url = this.generateMediaUrl({ fileOpenUrl: info.fileOpenUrl });
        this.$refs['myQuillEditor'].quill.insertEmbed(index, 'video', url, Quill.sources.USER);
      });
      this.$refs['yUpload'].clearFiles();
    },
  },
  watch:{
    'disabled'(){
      this.doWatchDisabled()
    }
  }
}
</script>

<style scoped lang="less">
.YRichText{
  &.quill-disabled{
    /deep/.ql-toolbar{
      display: none;
    }
    /deep/.ql-container{
      height: 100%;
      border-top: 1px solid #ccc!important;
    }
  }
  /deep/ *, /deep/*:before{
    vertical-align: top;
  }
  /deep/.ql-toolbar{
    height: 42px;
    >.ql-formats{
      vertical-align: top;
    }
  }
}
</style>
